import Swiper from '../../../../bower_components/swiper/dist/js/swiper.min.js'

$(function () {
  init()

  window.productInfo = null
  window.time = 0
  getProductInfo()
  setInterval(() => {
    if (productInfo) {
      if (productInfo.buyingStartAt - new Date().getTime() / 1000 > 0) {
        // 活动还没开始
        // console.log('活动还没开始')
        if (!time) setCountDown(JSON.parse(JSON.stringify(productInfo.buyingStartAt)))
        if ($(window).scrollTop() > 400) {
          // 显示底部购买条 隐藏购物车
          $('.buy-cart').hide()
          $('.buy-bottom-bar').show()
        } else {
          // 显示购物车 隐藏底部购买条
          $('.buy-cart').hide()
          $('.buy-bottom-bar').hide()
        }
      } else if (productInfo.totalSoldCount >= productInfo.totalLimit) {
        // 活动名额已满
        // console.log('活动名额已满')
        $('.count-down').hide()
        $('.buy-cart').hide()
        $('.buy-bottom-bar').hide()
        $('.sale-over').show()
      } else {
        // 活动进行中
        // console.log('活动进行中')
        $('.count-down').hide()
        $('.buy-btn').show()
        $('.count-person').show()
        if ($(window).scrollTop() > 400) {
          // 显示底部购买条 隐藏购物车
          $('.buy-cart').hide()
          $('.buy-bottom-bar').show()
        } else {
          // 显示购物车 隐藏底部购买条
          $('.buy-cart').show()
          $('.buy-bottom-bar').hide()
        }
      }
    }
  }, 100)
  setInterval(getProductInfo, 10000)

  function getProductInfo () {
    $.ajax({
      type: 'GET',
      url: `${apiUrl}/s/products/${productId}`,
      contentType: 'application/json',
      success: res => {
        console.log(res)
        window.productInfo = res
        $('.progress').css('width', `${productInfo.totalSoldCount * 100 / productInfo.totalLimit}%`)
        $('.total-num').text(productInfo.totalLimit)
        $('.count-person > .text > .red').text(`${Math.max(0, productInfo.totalLimit - productInfo.totalSoldCount)}`)
      },
      error: err => {
        const error = JSON.parse(err.response)
        console.error(error.message)
      }
    })
  }

  $('.buy-cart, .buy-btn').off('click').on('click', e => window.location.href = orderUrl)

  function setCountDown (endAt) {
    var time = setInterval(() => {
      const nowAt = parseInt(new Date().getTime() / 1000)
      const diff = endAt - nowAt
      if (diff < 0) {
        $('.count-down').hide()
        $('.count-person').show()
        $('.buy-btn').show()
        clearInterval(time)
        return
      }
      const day = Math.floor(diff / 60 / 60 / 24)
      let hour = Math.floor(diff / 60 / 60 % 24)
      hour = hour < 10 ? `0${hour}` : hour
      let min = Math.floor(diff / 60 % 60)
      min = min < 10 ? `0${min}` : min
      let sec = Math.floor(diff % 60)
      sec = sec < 10 ? `0${sec}` : sec

      const dayTime = `${day}&nbsp;天&nbsp;${hour}&nbsp;:&nbsp;${min}`
      const secTime = `${hour}&nbsp;:&nbsp;${min}&nbsp;:&nbsp;${sec}`
      $('.count-down .time').html(day > 0 ? dayTime : secTime)
      $('.count-down').show()
    }, 1000)
  }
})

function init() {
  window.campaign = '1v1'
  window.productId = window.campaignProduct
  window.apiUrl = 'https://gate.97kid.com'
  window.campUrl = `${window.location.protocol}//${window.location.host}/wx/one`
  window.orderUrl = `${window.location.protocol}//${window.location.host}/wx/order${Math.ceil(Math.random() * 100)}?pid=${productId}&_c=${campaign}`
  window.avPrefix = 'p009'
  window.analytics = AV.analytics({
    appId: 'antYy9lOFi5mkU9QKjtYmRLM-gzGzoHsz',
    appKey: 'jqyWxLyobpsmdwsJddJlDheb',
    channel: utils.isWeChat() ? 'weixin' : ''
  })
  new Swiper ('.swiper-container', {
    // Optional parameters
    direction: 'horizontal',
    loop: true,

    // Auto play
    autoplay: {
      delay: 3000,
    },

    // If we need pagination
    pagination: {
      el: '.swiper-pagination',
    }
  })
  setShare()
}

function setShare () {
  window.wxconfig = new WxConfig(wechatConfig, '1v1')
  window.shareFlag = ''
  const userInfo = JSON.parse(window.localStorage.getItem('QKidsUserInfo'))
  if (userInfo && userInfo.shareFlag) window.shareFlag = userInfo.shareFlag
  if (utils.isWeChat()) wxconfig.activeShare(shareFlag, '', {
    title: '【5折福利】久趣1对1北美精英外教在线教学，仅500名额！',
    desc: '适合4-12岁，专属外教固定时间，让孩子爱上英语！',
    link: `${campUrl}${Math.ceil(Math.random() * 100)}?_c=${campaign}&_r=${shareFlag}`,
    imgUrl: 'https://static-app.97kid.com/site-student/public/mobile/campaign/1v1/img/share.jpg',
    success: target => {
      analytics.send({
        event: `${avPrefix}_share_success`,
        attr: {target}
      })
    }
  })
}